<template>
  <div class="menu-management">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-area mb-20">
        <el-form :model="searchForm" inline>
          <el-form-item label="菜单类型">
            <el-input
              v-model="searchForm.type"
              placeholder="请选择菜单类型"
              clearable
              style="width: 300px"
            >
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮 -->
      <div class="action-area mb-20">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增菜单
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="菜单名称" />
        <el-table-column prop="path" label="路径" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="sortId" label="排序" width="80" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area mt-20">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 菜单表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="父级菜单" prop="parentId">
          <el-select
            v-model="formData.parentId"
            :min="0"
            placeholder="请选择父级菜单"
          >
            <el-option
              v-for="item in tableData.filter((i) => i.type === 0)"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio :label="0">菜单</el-radio>
            <el-radio :label="1">API</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="formData.path" placeholder="请输入路径" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sortId">
          <el-input-number v-model="formData.sortId" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="submitLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
} from "element-plus";
import { getMenuList, createMenu, updateMenu, deleteMenu } from "@/api/system";
import type {
  Menu,
  MenuCreateParams,
  MenuUpdateParams,
  MenuListParams,
} from "@/api/types";

// 搜索表单
const searchForm = reactive({
  type: undefined as number | undefined,
});

// 表格数据
const tableData = ref<Menu[]>([]);
const loading = ref(false);

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0,
});

// 加载数据
const loadData = async () => {
  try {
    loading.value = true;
    const params: MenuListParams = {
      page: pagination.page,
      size: pagination.size,
      type: searchForm.type || 0, // 如果没有选择类型，传0表示查询菜单
    };

    const response = await getMenuList(params);
    tableData.value = response.data.data || [];
    pagination.total = response.data.total || 0;
  } catch (error) {
    console.error("加载菜单列表失败:", error);
    ElMessage.error("加载菜单列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  loadData();
};

// 重置
const handleReset = () => {
  searchForm.type = undefined;
  pagination.page = 1;
  loadData();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.page = 1;
  loadData();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  loadData();
};
// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref("");
const submitLoading = ref(false);

// 表单
const formRef = ref<FormInstance>();

// 表单数据
const formData = reactive({
  id: undefined as number | undefined,
  parentId: 0,
  name: "",
  path: "",
  remark: "",
  sortId: 0,
  type: 0,
  extraData: {},
});

const formRules: FormRules = {
  name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择菜单类型", trigger: "change" }],
  path: [{ required: true, message: "请输入路径", trigger: "blur" }],
};

// 新增菜单
const handleAdd = () => {
  dialogTitle.value = "新增菜单";
  resetForm();
  dialogVisible.value = true;
};

// 编辑菜单
const handleEdit = (row: Menu) => {
  dialogTitle.value = "编辑菜单";
  Object.assign(formData, {
    id: row.id,
    parentId: row.parentId || 0,
    name: row.name,
    path: row.path || "",
    remark: row.remark || "",
    sortId: row.sortId || 0,
    type: row.type,
  });
  dialogVisible.value = true;
};

// 删除菜单
const handleDelete = async (row: Menu) => {
  try {
    await ElMessageBox.confirm(`确定要删除菜单"${row.name}"吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 调用删除接口
    const response: any = await deleteMenu({ id: row.id });

    if (response.code === 0) {
      ElMessage.success("删除成功");
      loadData();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    console.error("删除菜单失败:", error);
    // 用户取消删除或其他错误
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();

    if (formData.id) {
      // 调用编辑接口
      const updateParams: MenuUpdateParams = {
        id: formData.id,
        extraData: formData.extraData,
        name: formData.name,
        parentId: formData.parentId,
        path: formData.path,
        remark: formData.remark,
        sortId: formData.sortId,
        type: formData.type,
      };

      await updateMenu(updateParams);
      ElMessage.success("编辑成功");
    } else {
      // 调用新增接口
      const createParams: MenuCreateParams = {
        extraData: formData.extraData,
        name: formData.name,
        parentId: formData.parentId,
        path: formData.path,
        remark: formData.remark,
        sortId: formData.sortId,
        type: formData.type,
      };

      await createMenu(createParams);
      ElMessage.success("新增成功");
    }

    dialogVisible.value = false;
    loadData();
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 取消
const handleCancel = () => {
  dialogVisible.value = false;
  resetForm();
};

// 对话框关闭
const handleDialogClose = () => {
  resetForm();
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    parentId: 0,
    name: "",
    path: "",
    remark: "",
    sortId: 0,
    type: 0,
    extraData: {},
  });
  formRef.value?.clearValidate();
};

// 组件挂载时加载数据
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.menu-management {
  padding: 0;
}

.action-area {
  margin-bottom: 20px;
}
</style>
